<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\MissionDeposit;
use App\Models\Order;
use App\Models\School;
use App\Models\SchoolWithdrawFund;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SchoolWithdrawFundForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $schoolId = $input['school_id'];
        $amount = $input['amount'];
        $availableAmount = $input['available_amount'];
        if (bcsub($amount, $availableAmount, 2) > 0) {
            return $this->response()->error('提现金额不足');
        }
        try {

            // 开始事务
            DB::beginTransaction();
            //添加学校提现记录
            SchoolWithdrawFund::create([
                'school_id' => $schoolId,
                'amount' => $amount,
            ]);
            // 提交事务
            DB::commit();
        } catch (\Exception $e) {
            // 发生错误，回滚事务
            DB::rollBack();
            // 处理异常
            return $this->response()->error(message: $e->getMessage());

        }
        return $this->response()->success('添加成功')->refresh();
    }

    // 构建表单
    public function form()
    {
        // 获取外部传递参数
        $school_id = $this->payload['id'] ?? null;
        $school = School::where('id', $school_id)->first();
        if ($school) {
            //总利润
            $totalHandlingFee = Order::where('school_id', $school->id)->where('status', 6)->sum('handling_fee');
            $totalOrderTakingFee = Order::where('school_id', $school->id)->where('status', 6)->sum('order_taking_fee');
            $totalAmount = Order::where('school_id', $school->id)->where('status', 6)->sum('amount');
            $totalProfit = $totalHandlingFee + $totalOrderTakingFee + $totalAmount;
            //与平台分成比例

            //可提现佣金
            $schoolWithdrawFund = SchoolWithdrawFund::where('school_id', $school->id)->sum('amount');
            $availableAmount = bcsub($totalProfit, $schoolWithdrawFund, 2);
            $this->text('total_profit', '总利润')->value($totalProfit)->readOnly();
            $this->text('share_ratio', '平台分成比例')->value($school->share_ratio)->readOnly();
            $this->text('available_amount', '可提现佣金')->value($availableAmount)->readOnly();
            $this->decimal('amount', '提现金额')->required();
            $this->hidden('school_id')->value($school->id);
        }
        $this->disableResetButton();
    }
}
